package com.lsq.wuyuge.interceptor;

import com.lsq.wuyuge.context.BaseContext;
import com.lsq.wuyuge.propertis.JwtPropertis;
import com.lsq.wuyuge.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtPropertis jwtpropertis;

    /**
     *校验jwt
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("jwt拦截器校验中~~~");
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //获取jwt
        String token = request.getHeader(jwtpropertis.getTokenName());
        //校验
        try {
            log.info("jwt:{}",token);
            Claims claims = JwtUtil.paresToken(token, jwtpropertis.getSecretKey());
            Integer userId = claims.get("userId",Integer.class);
            log.info("当前用户id:{}",userId);
            BaseContext.setCurrentId(Long.valueOf(userId));
            log.info("jwt校验成功");
            return true;
        }catch (Exception e){
            log.error("jwt校验失败");
            response.setStatus(401);
            return false;
        }
    }
}
